package com.zhangx.mq.demo.rabbit.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName SendMessageController
 * @Description 发送直接消息
 * @Author zhangx
 * @Date 2021/2/19 15:40
 **/
@Slf4j
@RestController
public class SendDirectMessageController {

    /**
     * 单个发送者不能超过2048个channel
     * 828ms发送2048条数据，672ms消费完
     */
    private static final int MAX_THREADS = 100;

    private static CountDownLatch cdl = new CountDownLatch(MAX_THREADS);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitTemplate newRabbitTemplate;

    @GetMapping("/sendDirectMessage")
    public String sendDirectMessage() {

        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        for (int i = 0; i < MAX_THREADS; i++) {
            Thread t = new Thread(()->{
                cdl.countDown();
                try {
                    cdl.await();
                    String messageId = String.valueOf(UUID.randomUUID());
                    String messageData = "test message, hello!";
                    String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
                    Map<String,Object> map=new HashMap<>();
                    map.put("messageId",messageId);
                    map.put("messageData",messageData);
                    map.put("createTime",createTime);
                    rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);
                    log.info("发送消息完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }

        return "ok";
    }

    @GetMapping("/direct/{key}")
    public String direct(@PathVariable("key")String key){
        String msg = "key("+key+"),exchange(DirectExchange)-"+System.currentTimeMillis();
        newRabbitTemplate.convertAndSend("DirectExchange",key,msg);
        log.info("发送消息：{}",msg);
        return "success";
    }

}
